package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class AccountService {
    @Autowired
    private AccountMapper accountMapper;

    private String getEncryptedPassword(String salt, String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance( "MD5" );
        //将用户名作为盐拼接到密码后方
        String originText = password.concat( salt );
        md.update( originText.getBytes() );
        byte[] digest = md.digest();
        String hashText = DatatypeConverter.printHexBinary(digest).toUpperCase();

        return hashText;
    }

    public List<Account> getAllAcount() {
        return accountMapper.getAllAcount();
    }

    public Account getAccount(String username) {
        return accountMapper.getAccountByUsername(username);
    }

    public Account getAccount(String username, String password) throws NoSuchAlgorithmException {
        Account account = new Account();
        account.setUsername(username);
        //将用户名作为盐
        account.setPassword(getEncryptedPassword( username, password ));
        return accountMapper.getAccountByUsernameAndPassword(account);
    }

    public void insertAccount(Account account) throws NoSuchAlgorithmException {
        account.setPassword( getEncryptedPassword( account.getUsername(), account.getPassword() ) );
        accountMapper.insertAccount(account);
        accountMapper.insertProfile(account);
        accountMapper.insertSignon(account);
    }

    public void removeAccount(Account account) {
        accountMapper.removeAccount(account);
        accountMapper.removeSignon(account);
        accountMapper.removeProfile(account);
    }

    public void updateAccount(Account account) throws NoSuchAlgorithmException {
        if (account.getPassword() != null && account.getPassword().length() > 0) {
            account.setPassword( getEncryptedPassword( account.getUsername(), account.getPassword() ) );
            accountMapper.updateSignon(account);
        }
        accountMapper.updateAccount(account);
        accountMapper.updateProfile(account);
    }

}
